package com.game.sdk.pay.heepay;


import org.json.JSONException;
import org.json.JSONObject;

import com.game.sdk.YTAppService;
import com.game.sdk.domain.PaymentCallbackInfo;
import com.game.sdk.domain.PaymentErrorMsg;
import com.game.sdk.domain.ResultCode;
import com.game.sdk.init.NetCallBack;
import com.game.sdk.pay.PayUtil;
import com.game.sdk.ui.ChargeActivity;
import com.game.sdk.util.ActivityTaskManager;
import com.game.sdk.util.Constants;
import com.game.sdk.util.DialogUtil;
import com.game.sdk.util.GetDataImpl;
import com.game.sdk.util.Logger;
import com.game.sdk.util.MResource;
import com.game.sdk.util.PaymentInfo;
import com.game.sdk.util.Util;
import com.game.sdk.view.ChargeView;
import com.heepay.plugin.api.HeepayPlugin;
import com.junnet.heepay.service.HeepaySDKConstant;
import com.junnet.heepay.service.HeepayServiceHelper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class HeeQuickPayActivity extends Activity implements OnClickListener {
	private String orderid;
	private double charge_money;// 需要充值的金额
	private String serverid;// 充值的服务器id；
	private String productname;// 充值游戏名称
	private String productdesc;// 产品描述
	private String fcallbackurl;// 充值回调地址，由游戏方传递
	private String roleid;// 角色id；
	private String attach;// 游戏方传递的拓展参数
	private Context ctx;
	private String _payType, _agentBillNo;
	private Button btn_goto_pay;
	private TextView tv_username, tv_money, tv_back;
	// 汇付宝安全支付服务Logo是否需要隐藏
	private boolean isLogoHidden;
	private Bundle _payInfoBundle;
	private HeepayServiceHelper _heepayHelper;
	private PaymentInfo _paymentInfo;
	private static final int INIT_RESULT = 1001;
	private static final int QUERY_RESULT = 1002;

	private String pay_id;
	private String order_id;
	private String pay_token;
	private String tokenid;
	private String agentid;
	private String billno;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message message) {
			switch (message.what) {

			case HeepaySDKConstant.PAYRESULT_OVER:
				// Log.v(SHOW_TAG, message.obj.toString());
				// 不允许被赋值为1/0/-1,因已有对应的支付状态
				int status = -2;
				try {
					JSONObject object = new JSONObject(message.obj.toString());

					status = object.getInt("bill_status");

				} catch (JSONException e) {
					e.printStackTrace();
				}
				if (status == 1) {
					Util.onPayReqSuc("支付成功", charge_money,
							HeeQuickPayActivity.this);
				} else if (status == 0) {
					PayUtil.queryOrder(orderid, charge_money,
							HeeQuickPayActivity.this);
				} else {
					Util.onPayReqFail("支付失败", charge_money,
							HeeQuickPayActivity.this);
				}
				break;
			case HeepaySDKConstant.CHECK_INSTALL:

				startHeepayService();
				break;

			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(MResource.getIdByName(this, Constants.Resouce.LAYOUT,
				"sdk_hee_pay"));
		this.ctx = getApplicationContext();

		tv_money = (TextView) findViewById(MResource.getIdByName(ctx,
				Constants.Resouce.ID, "tv_money"));
		tv_username = (TextView) findViewById(MResource.getIdByName(ctx,
				Constants.Resouce.ID, "tv_username"));
		tv_back = (TextView) findViewById(MResource.getIdByName(ctx,
				Constants.Resouce.ID, "tv_back"));
		btn_goto_pay = (Button) findViewById(MResource.getIdByName(ctx,
				Constants.Resouce.ID, "btn_goto_pay"));

		Intent intent = getIntent();
		roleid = intent.getStringExtra("roleid");
		serverid = intent.getStringExtra("serverid");
		charge_money = intent.getDoubleExtra("money", 0);
		productname = intent.getStringExtra("productname");
		productdesc = intent.getStringExtra("productdesc");
		fcallbackurl = intent.getStringExtra("fcallbackurl");

		tv_username.setText(YTAppService.userinfo.username);
		tv_money.setText(charge_money + "元");

		attach = intent.getStringExtra("attach");
		pay_id = intent.getStringExtra("pay_id");
		order_id = intent.getStringExtra("order_id");
		pay_token = intent.getStringExtra("pay_token");
		// _payType = "0";
		_payType = intent.getStringExtra("pay_type");
		btn_goto_pay.setOnClickListener(this);
		tv_back.setOnClickListener(this);
		pay();
	}

	public void pay() {
		if(!TextUtils.isEmpty(billno)&&!TextUtils.isEmpty(agentid)&&!TextUtils.isEmpty(tokenid)){
			payTask();
			return;
		}
		DialogUtil.showDialog(HeeQuickPayActivity.this, "正在努力的加载...");
		NetUtil.reqHeepayAll(YTAppService.userinfo.mem_id,
				YTAppService.userinfo.user_token, charge_money + "", pay_token,
				_payType, ctx, new NetCallBack() {

					@Override
					public void onInitSuccess(ResultCode result) {
						if (!TextUtils.isEmpty(result.data)) {
							try {
								JSONObject jo = new JSONObject(result.data);
								tokenid = jo.getString("c");
								agentid = jo.getString("b");
								billno = jo.getString("a");
								payTask();
							} catch (JSONException e) {
								Util.showNetFailToast(ctx, "数据转化异常", result);
								HeeQuickPayActivity.this.finish();
								e.printStackTrace();
							}
						} else {
							Util.onPayReqFail("服务端异常请稍候重试！", charge_money,
									HeeQuickPayActivity.this);
						}
					}

					@Override
					public void onInitFail(ResultCode result) {
						Util.onPayReqFail("请求服务器异常", charge_money,
								HeeQuickPayActivity.this);
						HeeQuickPayActivity.this.finish();
					}
				});
	}

	protected void payTask() {
		_paymentInfo = new PaymentInfo();

		_paymentInfo.setTokenID(tokenid);// tokenid
		_paymentInfo.setAgentId(agentid);// agentid
		_paymentInfo.setBillNo(billno);// orderid
		_heepayHelper = new HeepayServiceHelper(
				HeeQuickPayActivity.this);
		_heepayHelper.isHeepayServiceInstalled(handler);
	}

	/**
	 * 启动汇付宝安全支付服务
	 */
	private void startHeepayService() {
		if (_paymentInfo == null) {
			Toast.makeText(this, "请先进行支付初始化", Toast.LENGTH_SHORT).show();
			return;
		}
		_payInfoBundle = new Bundle();
		_payInfoBundle.putString("tid", _paymentInfo.getTokenID());
		_payInfoBundle.putInt("aid",
				Integer.parseInt(_paymentInfo.getAgentId()));

		_payInfoBundle.putString("bn", _paymentInfo.getBillNo());
		// 微信支付需要为隐藏汇付宝Logo(true)
		_payInfoBundle.putBoolean("hidden", isLogoHidden);
		_heepayHelper = new HeepayServiceHelper(HeeQuickPayActivity.this);
		_heepayHelper.pay(_payInfoBundle, handler,
				HeepaySDKConstant.REQUEST_PAY);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (null != tv_back && v.getId() == tv_back.getId()) {
			PayUtil.queryOrder(orderid, charge_money, HeeQuickPayActivity.this);
			return;
		}
		if (null != btn_goto_pay && v.getId() == btn_goto_pay.getId()) {
			pay();
		}
	}

	@Override
	public void onBackPressed() {
		PayUtil.queryOrder(orderid, charge_money, HeeQuickPayActivity.this);
	}
}
